﻿using System.Windows;
using System.Windows.Controls;
using BrainTechLLC;
using System.Windows.Data;
using ImageAppViewModels;
using BrainTechLLC.ThreadSafeObjects;
using System.Windows.Threading;
using System;

namespace WpfImageDuplicates
{
    /// <summary>
    /// Interaction logic for ThumbViewBottom.xaml
    /// </summary>
    public partial class ThumbViewBottom : UserControl
    {
        public bool _wiredUp;
        protected DispatcherTimer _timer;
        protected FileImageViewModel _vm;
        protected ThumbnailView _ThumbnailView;

        public static ThreadSafeCounter timers = new ThreadSafeCounter();
        public static ThreadSafeCounter wiredUp = new ThreadSafeCounter();

        public static readonly DependencyProperty FileImageViewModelProperty =
            DependencyProperty.Register("FileImageViewModel", typeof(FileImageViewModel), typeof(ThumbViewBottom), new PropertyMetadata(null, OnFileImageViewModelPropertyChanged));

        public FileImageViewModel FileImageViewModel
        {
            get { return (FileImageViewModel)GetValue(FileImageViewModelProperty); }
            set { _vm = value; SetValue(FileImageViewModelProperty, value); }
        }

        public ThumbnailView ThumbnailView
        {
            get { return _ThumbnailView; }
            set { _ThumbnailView = value; }
        }

        private static void OnFileImageViewModelPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ThumbViewBottom source = d as ThumbViewBottom;
            source.UpdateFileImageViewModel(e.OldValue as FileImageViewModel, e.NewValue as FileImageViewModel);
        }

        private void UpdateFileImageViewModel(FileImageViewModel viewModelOld, FileImageViewModel viewModelNew)
        {
            g.DataContext = viewModelNew;

            if (viewModelNew == null)
            {
                if (_wiredUp)
                {
                    DeWire();
                }
            }
            else
            {
                InitializeDisplay();
                CheckWireUp();
            }
        }

        private void CheckWireUp()
        {
            if (!_wiredUp)
            {
                WireUp();
                if (_timer != null)
                {
                    _timer.Stop();
                    _timer.Tick -= _timer_Tick;
                    _timer = null;
                    timers.Decrement();
                }
                _timer = new DispatcherTimer() { Interval = new System.TimeSpan(0, 0, 0, 2, 800) };
                _timer.Tick += new System.EventHandler(_timer_Tick);
                timers.Increment();
            }
        }

        void _timer_Tick(object sender, System.EventArgs e)
        {
            CheckTimer();
        }

        public ThumbViewBottom()
        {
            InitializeComponent();
        }

        private bool CheckTimer()
        {
            bool mustDoSomething = false;
            if (FileImageViewModel == null && _wiredUp)
            {
                mustDoSomething = true;
            }
            else if (_wiredUp && FileImageViewModel != null && !FileImageViewModel.ThumbVisible)
            {
                mustDoSomething = true;
            }
            else if (!_wiredUp && FileImageViewModel != null && FileImageViewModel.ThumbVisible)
            {
                mustDoSomething = true;
            }

            // May be able to take this out since it's on a dispatcher timer
            if (mustDoSomething)
            {
                //Dispatcher.BeginInvoke(new VoidDelegate(() =>
                //{
                if (FileImageViewModel == null)
                {
                    if (_wiredUp)
                    {
                        DeWire();
                    }
                }
                else
                {
                    if (_wiredUp && !FileImageViewModel.ThumbVisible)
                    {
                        DeWire();
                    }
                    else if (!_wiredUp && FileImageViewModel.ThumbVisible)
                    {
                        WireUp();
                    }
                }
                //}));
            }

            return false;
        }

        private void WireUp()
        {
            if (!_wiredUp)
            {
                _wiredUp = true;
                Window1.MainWindow.SettingsWatcher.SettingsViewModel.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(SettingsViewModel_PropertyChanged);
                wiredUp.Increment();
            }
        }

        private void DeWire()
        {
            if (_wiredUp)
            {
                _wiredUp = false;
                wiredUp.Decrement();
                Window1.MainWindow.SettingsWatcher.SettingsViewModel.PropertyChanged -= SettingsViewModel_PropertyChanged;
                if (_timer != null)
                {
                    _timer.Stop();
                    _timer.Tick -= _timer_Tick;
                    _timer = null;
                    timers.Decrement();
                }
            }
        }

        void SettingsViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "NoInfoDisplayedBelowThumbs")
            {
                this.Visibility = (Settings.Values.NoInfoDisplayedBelowThumbs) ? Visibility.Collapsed : Visibility.Visible;
            }
            else if (e.PropertyName == "ThumbShowFileDate")
            {
                txtFileDate.Visibility = (Settings.Values.ThumbShowFileDate) ? Visibility.Visible : Visibility.Collapsed;
                SetOrClearBinding(txtFileDate, !Settings.Values.ThumbShowFileDate, txtFileDate.Tag as string);
            }
            else if (e.PropertyName == "ThumbShowFileName")
            {
                txtFileName.Visibility = (Settings.Values.ThumbShowFileName) ? Visibility.Visible : Visibility.Collapsed;
                SetOrClearBinding(txtFileNameOnly, !Settings.Values.ThumbShowFileName, txtFileNameOnly.Tag as string);
            }
            else if (e.PropertyName == "ThumbShowFileSize")
            {
                txtShowFileSize.Visibility = (Settings.Values.ThumbShowFileSize) ? Visibility.Visible : Visibility.Collapsed;
                SetOrClearBinding(txtShowFileSize, !Settings.Values.ThumbShowFileSize, txtShowFileSize.Tag as string);
            }
            else if (e.PropertyName == "ThumbShowFullPath")
            {
                txtShowFullPath.Visibility = (Settings.Values.ThumbShowFullPath) ? Visibility.Visible : Visibility.Collapsed;
                SetOrClearBinding(txtShowFullPath, !Settings.Values.ThumbShowFullPath, txtShowFullPath.Tag as string);
            }
            else if (e.PropertyName == "ThumbShowDimensions")
            {
                txtDimensions.Visibility = (Settings.Values.ThumbShowDimensions) ? Visibility.Visible : Visibility.Collapsed;
                SetOrClearBinding(txtDimensions, !Settings.Values.ThumbShowDimensions, txtDimensions.Tag as string);
            }
            else if (e.PropertyName == "ThumbShowFileDescriptions")
            {
                txtDescription.Visibility = (Settings.Values.ThumbShowFileDescriptions) ? Visibility.Visible : Visibility.Collapsed;
                SetOrClearBinding(txtDescription, !Settings.Values.ThumbShowFileDescriptions, txtDescription.Tag as string);
            }
        }

        public void InitializeDisplay()
        {
            this.Visibility = (Settings.Values.NoInfoDisplayedBelowThumbs) ? Visibility.Collapsed : Visibility.Visible;

            if (!Settings.Values.NoInfoDisplayedBelowThumbs)
            {
                txtFileDate.Visibility = (Settings.Values.ThumbShowFileDate) ? Visibility.Visible : Visibility.Collapsed;
                txtFileName.Visibility = (Settings.Values.ThumbShowFileName) ? Visibility.Visible : Visibility.Collapsed;
                txtShowFileSize.Visibility = (Settings.Values.ThumbShowFileSize) ? Visibility.Visible : Visibility.Collapsed;
                txtShowFullPath.Visibility = (Settings.Values.ThumbShowFullPath) ? Visibility.Visible : Visibility.Collapsed;
                txtDimensions.Visibility = (Settings.Values.ThumbShowDimensions) ? Visibility.Visible : Visibility.Collapsed;
                txtDescription.Visibility = (Settings.Values.ThumbShowFileDescriptions) ? Visibility.Visible : Visibility.Collapsed;

                //Dispatcher.BeginInvoke(() =>
                //{
                SetOrClearBinding(txtFileDate, !Settings.Values.ThumbShowFileDate, txtFileDate.Tag as string);
                SetOrClearBinding(txtFileNameOnly, !Settings.Values.ThumbShowFileName, txtFileNameOnly.Tag as string);
                SetOrClearBinding(txtShowFileSize, !Settings.Values.ThumbShowFileSize, txtShowFileSize.Tag as string);
                SetOrClearBinding(txtShowFullPath, !Settings.Values.ThumbShowFullPath, txtShowFullPath.Tag as string);
                SetOrClearBinding(txtDimensions, !Settings.Values.ThumbShowDimensions, txtDimensions.Tag as string);
                SetOrClearBinding(txtDescription, !Settings.Values.ThumbShowFileDescriptions, txtDescription.Tag as string);
                //}, DispatcherPriority.Render);
            }
        }

        private void SetOrClearBinding(FrameworkElement tb, bool clearBinding, string propName)
        {
            if (!string.IsNullOrEmpty(propName))
            {
                if (clearBinding)
                {
                    BindingOperations.ClearBinding(tb, TextBlock.TextProperty);
                }
                else
                {
                    Binding b = new Binding(propName)
                    {
                        Mode = BindingMode.OneWay,
                        UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
                    };
                    tb.SetBinding(TextBlock.TextProperty, b);
                }
            }
        }

        private void txtFileNameOnly_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            FileImageViewModel.NewFileName = FileImageViewModel.FileNameOnly;
            FileImageViewModel.EnteredFileNameEditMode = true;
            Dispatcher.BeginInvoke(() =>
            {
                txtChangeFileName.Focus();
                txtChangeFileName.SelectAll();
            });
        }

        private void txtChangeFileName_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Escape)
            {
                FileImageViewModel.EnteredFileNameEditMode = false;
                e.Handled = true;
            }
            else if (e.Key == System.Windows.Input.Key.Enter)
            {
                var dir = System.IO.Path.GetDirectoryName(FileImageViewModel.FileName);
                FileImageViewModel.NewFileName = dir + "\\" + txtChangeFileName.Text;
                if (!string.IsNullOrEmpty(FileImageViewModel.NewFileName) && FileImageViewModel.FileName != FileImageViewModel.NewFileName)
                {
                    byte[] bytes = App.DataProvider.ReadAllImageBytes(FileImageViewModel.FileName);
                    App.DataProvider.WriteAllBytes(FileImageViewModel.NewFileName, bytes);
                    App.DataProvider.Delete(FileImageViewModel.FileName);
                    _ThumbnailView._parentCollectionView.ThumbsHandler._thumbsByFileName.Remove(FileImageViewModel.FileName);
                    FileImageViewModel.FileName = FileImageViewModel.NewFileName;
                    _ThumbnailView._parentCollectionView.ThumbsHandler._thumbsByFileName.Add(FileImageViewModel.NewFileName, this.ThumbnailView);
                    FileImageViewModel.NewFileName = null;

                }
                e.Handled = true;
            }
        }
    }
}
